﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using Microsoft.Win32;
using System.ComponentModel;
using System.Reflection;
using System.Runtime.Remoting.Messaging;
using ICSharpCode.SharpZipLib.Zip;

namespace LiveWriterBackupWPF
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class frmMain : Window
    {
        private bool _settingsPlayed = false;
        private bool _postsPlayed = false;
        private bool _pluginsPlayed = false;
        private bool _autoLoadedFile = false;
        string _fileName = "";
        string _tempFolder = string.Format(@"{0}SJL\", System.IO.Path.GetTempPath());
        BackgroundWorker _checkUpdates;
        WLBSettings defaultsettings;

        public frmMain()
        {
            
            InitializeComponent();
            defaultsettings = new WLBSettings();
            defaultsettings.GrabSettings();
            SetSettings(defaultsettings);
            this.Loaded += new RoutedEventHandler(frmMain_Loaded);         
            this.Title = string.Format("{0} ({1})", AssemblyInfo.AssemblyTitle, AssemblyInfo.AssemblyVersion);
            canBackup.MainForm = this;
            canAbout.MainForm = this;
            if (!WLMisc.IsAnAdministrator())
            {
                btnRestore.Content = "Restore (Please restart program as Administrator)"; // Work Item #1683 http://www.codeplex.com/WLWBackup/WorkItem/View.aspx?WorkItemId=1683
                btnRestore.IsEnabled = false;
            }
            _checkUpdates = GetUpdatesWorker();

        }

        // Work Item #1736 http://www.codeplex.com/WLWBackup/WorkItem/View.aspx?WorkItemId=1736
        #region Check for updates
        private BackgroundWorker GetUpdatesWorker()
        {
            BackgroundWorker result = new BackgroundWorker();
            result.WorkerReportsProgress = false;
            result.WorkerSupportsCancellation = false;
            result.DoWork += new DoWorkEventHandler(_checkUpdates_DoWork);
            result.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_checkUpdates_RunWorkerCompleted);
            return result;
        }

        void _checkUpdates_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            object[] threadResult = e.Result as object[];
            if ((bool)threadResult[0])
            {
                string updateURL = threadResult[1].ToString();
                System.Windows.Forms.DialogResult result =
                        System.Windows.Forms.MessageBox.Show("There is a newer version available, would you like to download the installer?",
                        "Newer Version Available",
                        System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Question);
                if (result == System.Windows.Forms.DialogResult.Yes)
                {
                    System.Diagnostics.Process.Start(updateURL);
                }
            }
            txtbStatus.Text = string.Empty;
        }

        void _checkUpdates_DoWork(object sender, DoWorkEventArgs e)
        {
            string updateURL = string.Empty;
            if (Updates.CheckForUpdates(out updateURL))
            {
                e.Result = new object[] { true, updateURL };
            }
            else
            {
                System.Windows.Forms.MessageBox.Show("There was no newer version to download this time.",
                    "No New Version Available",
                    System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
                e.Result = new object[] { false, "" };
            }
        }
        #endregion

        void frmMain_Loaded(object sender, RoutedEventArgs e)
        {
            if (Application.Current.Properties["Restart"] != null)
            {
                bool restart = Convert.ToBoolean(Application.Current.Properties["Restart"]);
                if (restart)
                {
                    this.Close();
                }
            }
            if (Application.Current.Properties["FileName"] != null &&
            Application.Current.Properties["FileName"].ToString().Length > 0)
            {
                _fileName = (string)Application.Current.Properties["FileName"];
                if (File.Exists(_fileName))
                {
                    _autoLoadedFile = true;
                    btnRestore_Click(this, null);
                }
                else
                {
                    _fileName = "";
                }
            }
            else
            {
                // Check whether we need to auto check for updates
                if (defaultsettings.AutoUpdate && !_autoLoadedFile)
                {
                    linklabelCheckForUpdates_Click(this, null);
                }
            }
            
            if (!Directory.Exists(_tempFolder))
            {
                Directory.CreateDirectory(_tempFolder);
            }
            

        }

        #region Animation events
        private void txblSettings_MouseEnter(object sender, MouseEventArgs e)
        {
            Storyboard _settingsMouseOver = (Storyboard)this.Resources["SettingsMouseOver"];
            Storyboard _postsMouseOut = (Storyboard)this.Resources["PostsMouseOut"];
            Storyboard _pluginsMouseOut = (Storyboard)this.Resources["PluginsMouseOut"];

            if (_postsPlayed)
            {
                _postsMouseOut.Begin();
                _postsPlayed = false;
            }
            if (_pluginsPlayed)
            {
                _pluginsMouseOut.Begin();
                _pluginsPlayed = false;
            }
            if (!_settingsPlayed)
            {
                _settingsMouseOver.Begin();
                _settingsPlayed = true;
            }
        }

        private void txblPosts_MouseEnter(object sender, MouseEventArgs e)
        {
            Storyboard _settingsMouseOut = (Storyboard)this.Resources["SettingsMouseOut"];
            Storyboard _postsMouseOver = (Storyboard)this.Resources["PostsMouseOver"];
            Storyboard _pluginsMouseOut = (Storyboard)this.Resources["PluginsMouseOut"];

            if (!_postsPlayed)
            {
                _postsMouseOver.Begin();
                _postsPlayed = true;
            }
            if (_pluginsPlayed)
            {
                _pluginsMouseOut.Begin();
                _pluginsPlayed = false;
            }
            if (_settingsPlayed)
            {
                _settingsMouseOut.Begin();
                _settingsPlayed = false;
            }
        }

        private void txblPlugins_MouseEnter(object sender, MouseEventArgs e)
        {
            Storyboard _settingsMouseOut = (Storyboard)this.Resources["SettingsMouseOut"];
            Storyboard _postsMouseOut = (Storyboard)this.Resources["PostsMouseOut"];
            Storyboard _pluginsMouseOver = (Storyboard)this.Resources["PluginsMouseOver"];

            if (_postsPlayed)
            {
                _postsMouseOut.Begin();
                _postsPlayed = false;
            }
            if (!_pluginsPlayed)
            {
                _pluginsMouseOver.Begin();
                _pluginsPlayed = true;
            }
            if (_settingsPlayed)
            {
                _settingsMouseOut.Begin();
                _settingsPlayed = false;
            }
        }
        #endregion

        private WLBSettings GetSettings()
        {
            WLBSettings settings = new WLBSettings()
            {
                Drafts = (bool)chbxDrafts.IsChecked,
                IncludeBlogTemplates = (bool)chbxBlogTemplates.IsChecked,
                IncludeLinkGlossary = (bool)chbxLinkGlossary.IsChecked,
                Plugins = (bool)chbxAllPlugins.IsChecked,
                RecentPosts = (bool)chbxRecentPosts.IsChecked,
                Settings = (bool)chbxBlogs.IsChecked
            };
            return settings;
        }

        private void SetSettings(WLBSettings settings)
        {
            chbxDrafts.IsChecked = settings.Drafts;
            chbxBlogTemplates.IsChecked = settings.IncludeBlogTemplates;
            chbxLinkGlossary.IsChecked = settings.IncludeLinkGlossary;
            chbxAllPlugins.IsChecked = settings.Plugins;
            chbxRecentPosts.IsChecked = settings.RecentPosts;
            chbxBlogs.IsChecked = settings.Settings;
            chbxAutoUpdate.IsChecked = settings.AutoUpdate;
        }

        #region canMain Methods
        private void btnBackup_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.SaveFileDialog sFile = WLMisc.CreateSaveFile();
            WLBSettings settings = GetSettings();
            if (sFile.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                return;
            }
            if (Directory.Exists(_tempFolder))
            {
                try
                {
                    Directory.Delete(_tempFolder, true);
                }
                catch (Exception ex)
                {
                    WLBDebug.WriteToFile(ex.Message);
                    WLBDebug.WriteToFile(ex.ToString());
                }
            }
            _fileName = sFile.FileName;
            canMain.IsEnabled = false;
            canMain.Opacity = 0.1;
            Storyboard backupUp = (Storyboard)this.Resources["BackupUp"];
            backupUp.Begin();
            canBackup.StartBackup(settings, _fileName);            
        }

        private void btnRestore_Click(object sender, RoutedEventArgs e)
        {
            if (Directory.Exists(_tempFolder))
            {
                try
                {                    
                    Directory.Delete(_tempFolder, true);
                }
                catch (Exception ex)
                {
                    WLBDebug.WriteToFile(ex.Message);
                    WLBDebug.WriteToFile(ex.ToString());
                }
            }
            if (!_autoLoadedFile)
            {
                System.Windows.Forms.OpenFileDialog oFile = WLMisc.CreateDialog();
                if (oFile.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                {
                    return;
                }
                _fileName = oFile.FileName;
            }
            else
            {
                if (!WLMisc.IsAnAdministrator())
                {
                    return;
                }
            }
            if (File.Exists(_fileName))
            {
                System.Windows.Forms.DialogResult result =
                    System.Windows.Forms.MessageBox.Show("Restoring from this backup will remove any settings/posts/plugins currently on your system. \n Do you wish to continue?",
                    "Are you sure?",
                    System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Question);
                if (result == System.Windows.Forms.DialogResult.Yes)
                {
                    canMain.IsEnabled = false;
                    canMain.Opacity = 0.1;
                    Storyboard backupUp = (Storyboard)this.Resources["BackupUp"];
                    backupUp.Begin();
                    canBackup.StartRestore(_fileName);
                }
                else
                {
                    if (_autoLoadedFile)
                    {
                        this.Close();
                    }
                    return;
                }
            }
        }

        private void btnAbout_Click(object sender, RoutedEventArgs e)
        {
            Storyboard mainToAbout = (Storyboard)this.Resources["ShowAbout"];
            mainToAbout.Begin();
        }

        private void btnExit_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
        
        private void linklabelSaveDefault_Click(object sender, RoutedEventArgs e)
        {
            WLBSettings settings = GetSettings();
            settings.Save();
            txtbStatus.Text = "Settings saved."; // Work Item #1737 http://www.codeplex.com/WLWBackup/WorkItem/View.aspx?WorkItemId=1737
        }

        private void linklabelCheckForUpdates_Click(object sender, RoutedEventArgs e)
        {
            if (!_checkUpdates.IsBusy)
            {
                txtbStatus.Text = "Checking for updates...";
                _checkUpdates.RunWorkerAsync();
            }        
        }
        #endregion

        protected override void OnClosing(CancelEventArgs e)
        {

            if (Directory.Exists(_tempFolder))
            {
                try
                {
                    Directory.Delete(_tempFolder, true);
                }
                catch (Exception ex)
                {
                    WLBDebug.WriteToFile(ex.Message);
                    WLBDebug.WriteToFile(ex.ToString());
                }
            }
            base.OnClosing(e);
        }

        private void Image_MouseUp(object sender, MouseButtonEventArgs e)
        {
            System.Diagnostics.Process.Start("https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=3289441");
        }

        private void chbxAutoUpdate_Click(object sender, RoutedEventArgs e)
        {
            defaultsettings.AutoUpdate = (bool)chbxAutoUpdate.IsChecked;
        }

        
        
    }
}
